package org.noidler.demo;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.noidler.model.AnyThing;

import java.text.SimpleDateFormat;
import java.util.Map;

public class JSONUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public static String toJsonString(AnyThing gen) {
        try {

            return objectMapper.writeValueAsString(gen);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static <T> T toObj(String json, Class<T> clazz) {
        try {

            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <Y> Y map2Bean(Map<String, Object> map, Class<Y> clazz) {
        return objectMapper.convertValue(map, clazz);
    }

    public static <Y> Map<String, Object> bean2Map(Y bean) {
        return objectMapper.convertValue(bean, Map.class);
    }

    public static void main(String[] args) {
        AnyThing gen = MongoDb.gen();
        Map<String, Object> x = bean2Map(gen);
        System.out.println(x);
        System.out.println(map2Bean(x, AnyThing.class));
    }
}
